package com.ruoyi.web.controller.system;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.web.controller.config.YuruoAuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
//    @Autowired
//    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Resource
    private YuruoAuthProperties yuruoAuthProperties;



    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody LoginBody loginBody)
//    {
//        AjaxResult ajax = AjaxResult.success();
//        // 生成令牌
//        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//                loginBody.getUuid());
//        ajax.put(Constants.TOKEN, token);
//        return ajax;
//    }

    @GetMapping("/token/{code}")
    public AjaxResult getToken(@PathVariable("code") String code) {
        Assert.notNull(code,() -> new RuntimeException("授权码不能为空"));
        String url = String.format(yuruoAuthProperties.getTokenUrl(), yuruoAuthProperties.getClientId(), yuruoAuthProperties.getClientSecret(),code ,yuruoAuthProperties.getRedirectUri());
        String body = HttpRequest.post(url).execute().body();
        AjaxResult ajax = AjaxResult.success();
        Map<String, String> s = JSON.parseObject(body, new TypeReference<Map<String, String>>() {});
        String accessToken = s.get("access_token");
        if (StringUtils.isBlank(accessToken)) {
            return AjaxResult.error(401,"认证失败");
        }
        ajax.put(Constants.TOKEN, accessToken);
        return ajax;
    }


    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
